<?php
// 启动会话
session_start();

// 检查是否已登录
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

// 引入数据库配置
require '../config.php';

// 初始化成功消息变量
$success_message = '';

// 处理批量删除请求
if (isset($_POST['delete_selected']) && !empty($_POST['selected_tickets'])) {
    try {
        $selectedIds = implode(',', array_map('intval', $_POST['selected_tickets']));
        $deletedCount = count($_POST['selected_tickets']);
        
        // 首先获取要删除的工单的图片路径
        $sql = "SELECT screenshots FROM tickets WHERE id IN ($selectedIds)";
        $stmt = $pdo->query($sql);
        $screenshotRecords = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        // 删除物理图片文件
        $deletedImages = 0;
        $deleteErrors = [];
        
        foreach ($screenshotRecords as $screenshots) {
            if (!empty($screenshots)) {
                $imgPaths = explode(',', $screenshots);
                foreach ($imgPaths as $imgPath) {
                    // 确保使用绝对路径
                    $absolutePath = realpath(__DIR__ . '/../' . $imgPath);
                    
                    if ($absolutePath && file_exists($absolutePath)) {
                        if (unlink($absolutePath)) {
                            $deletedImages++;
                        } else {
                            $deleteErrors[] = "无法删除文件: $imgPath";
                            error_log("Failed to delete file: $absolutePath");
                        }
                    } else {
                        $deleteErrors[] = "文件不存在: $imgPath";
                        error_log("File not found: $absolutePath");
                    }
                }
            }
        }
        
        // 删除工单记录
        $sql = "DELETE FROM tickets WHERE id IN ($selectedIds)";
        $stmt = $pdo->query($sql);
        
        $success_message = "成功删除 $deletedCount 个工单和 $deletedImages 张图片！";
        if (!empty($deleteErrors)) {
            $success_message .= " 有 " . count($deleteErrors) . " 张图片删除失败，请查看日志。";
        }
    } catch(PDOException $e) {
        $error = '数据库错误: ' . $e->getMessage();
    }
}

// 处理单个删除请求
if (isset($_GET['delete_id'])) {
    try {
        $ticketId = intval($_GET['delete_id']);
        
        // 首先获取要删除的工单的图片路径
        $sql = "SELECT screenshots FROM tickets WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':id', $ticketId, PDO::PARAM_INT);
        $stmt->execute();
        $screenshots = $stmt->fetchColumn();
        
        // 删除物理图片文件
        $deletedImages = 0;
        $deleteErrors = [];
        
        if (!empty($screenshots)) {
            $imgPaths = explode(',', $screenshots);
            foreach ($imgPaths as $imgPath) {
                // 检查是否是URL（云存储）
                if (filter_var($imgPath, FILTER_VALIDATE_URL)) {
                    // 这里可以添加云存储删除逻辑
                    $deleteErrors[] = "无法删除云存储图片: $imgPath";
                    error_log("Cloud storage image cannot be deleted: $imgPath");
                } else {
                    // 确保使用绝对路径
                    $absolutePath = realpath(__DIR__ . '/../' . $imgPath);
                    
                    if ($absolutePath && file_exists($absolutePath)) {
                        if (unlink($absolutePath)) {
                            $deletedImages++;
                        } else {
                            $deleteErrors[] = "无法删除文件: $imgPath";
                            error_log("Failed to delete file: $absolutePath");
                        }
                    } else {
                        $deleteErrors[] = "文件不存在: $imgPath";
                        error_log("File not found: $absolutePath");
                    }
                }
            }
        }
        
        // 删除工单记录
        $sql = "DELETE FROM tickets WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':id', $ticketId, PDO::PARAM_INT);
        $stmt->execute();
        
        $success_message = "工单 #$ticketId 已成功删除，同时删除了 $deletedImages 张图片！";
        if (!empty($deleteErrors)) {
            $success_message .= " 有 " . count($deleteErrors) . " 张图片删除失败，请查看日志。";
        }
        // 清除URL中的delete_id参数
        header('Location: admin_dashboard.php');
        exit;
    } catch(PDOException $e) {
        $error = '数据库错误: ' . $e->getMessage();
    }
}

// 获取搜索关键词
$searchKeyword = '';
if (isset($_GET['search'])) {
    $searchKeyword = trim($_GET['search']);
}

// 获取工单数据，支持搜索
try {
    if (!empty($searchKeyword)) {
        $sql = "SELECT * FROM tickets WHERE 
                qq_number LIKE :keyword1 OR 
                feedback_type LIKE :keyword2 OR 
                description LIKE :keyword3 
                ORDER BY created_at DESC";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':keyword1', '%' . $searchKeyword . '%', PDO::PARAM_STR);
        $stmt->bindValue(':keyword2', '%' . $searchKeyword . '%', PDO::PARAM_STR);
        $stmt->bindValue(':keyword3', '%' . $searchKeyword . '%', PDO::PARAM_STR);
    } else {
        $sql = "SELECT * FROM tickets ORDER BY created_at DESC";
        $stmt = $pdo->query($sql);
    }
    $stmt->execute();
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $error = '数据库错误: ' . $e->getMessage();
}

// 退出登录功能
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// 获取当前用户名（假设管理员信息存储在admins表中）
try {
    $sql = "SELECT username FROM admins WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':id', $_SESSION['admin_id'], PDO::PARAM_INT);
    $stmt->execute();
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    $currentUsername = $admin['username'];
} catch(PDOException $e) {
    $error = '获取用户信息错误: ' . $e->getMessage();
}

// 处理修改用户名请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_username'])) {
    try {
        $newUsername = trim($_POST['new_username']);
        
        // 验证新用户名
        if (strlen($newUsername) < 3 || strlen($newUsername) > 20) {
            throw new Exception("用户名长度必须在3-20个字符之间");
        }
        
        // 更新用户名
        $sql = "UPDATE admins SET username = :username WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':username', $newUsername, PDO::PARAM_STR);
        $stmt->bindParam(':id', $_SESSION['admin_id'], PDO::PARAM_INT);
        $stmt->execute();
        
        // 更新会话中的用户名
        $_SESSION['admin_username'] = $newUsername;
        $currentUsername = $newUsername;
        
        echo json_encode(['status' => 'success', 'message' => '用户名已成功更新']);
        exit;
    } catch(Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}

// 处理修改密码请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    try {
        $currentPassword = $_POST['current_password'];
        $newPassword = $_POST['new_password'];
        $confirmPassword = $_POST['confirm_password'];
        
        // 验证密码
        if ($newPassword !== $confirmPassword) {
            throw new Exception("两次输入的新密码不一致");
        }
        
        if (strlen($newPassword) < 6) {
            throw new Exception("密码长度必须至少6个字符");
        }
        
        // 获取当前密码哈希
        $sql = "SELECT password FROM admins WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':id', $_SESSION['admin_id'], PDO::PARAM_INT);
        $stmt->execute();
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // 验证当前密码
        if (!password_verify($currentPassword, $admin['password'])) {
            throw new Exception("当前密码不正确");
        }
        
        // 更新密码
        $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $sql = "UPDATE admins SET password = :password WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':password', $newPasswordHash, PDO::PARAM_STR);
        $stmt->bindParam(':id', $_SESSION['admin_id'], PDO::PARAM_INT);
        $stmt->execute();
        
        echo json_encode(['status' => 'success', 'message' => '密码已成功更新']);
        exit;
    } catch(Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>✿ Another Dimension ✿</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&family=Ma+Shan+Zheng&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles_anime_admin.css">
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.11.3/dist/gsap.min.js"></script>
    <style>
        /* 基础样式 */
        .dashboard-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .header h1 {
            margin: 0;
            position: relative;
        }
        .header h1::before,
        .header h1::after {
            content: '✿';
            color: var(--secondary);
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.5rem;
        }
        .header h1::before {
            left: -30px;
        }
        .header h1::after {
            right: -30px;
        }
        .logout-btn, .smtp-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            margin-left: 10px;
        }
        .logout-btn {
            background-color: #e74c3c;
            color: white;
        }
        .smtp-btn {
            background-color: #2ecc71;
            color: white;
        }
        .header-actions {
            display: flex;
            align-items: center;
        }
        .logout-btn:hover {
            background-color: #c0392b;
        }
        .search-container {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .search-container input[type="text"] {
            padding: 8px 12px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-btn, .reset-btn, .delete-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }
        .search-btn {
            background-color: #3498db;
            color: white;
        }
        .search-btn:hover {
            background-color: #2980b9;
        }
        .reset-btn {
            background-color: #95a5a6;
            color: white;
        }
        .reset-btn:hover {
            background-color: #7f8c8d;
        }
        .delete-btn {
            background-color: #e74c3c;
            color: white;
        }
        .delete-btn:hover {
            background-color: #c0392b;
        }
        .bulk-actions {
            margin-bottom: 15px;
        }
        .bulk-actions .delete-btn {
            margin-bottom: 10px;
        }
        .success-message {
            background-color: #2ecc71;
            color: white;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            text-align: center;
        }
        .ticket-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        /* 响应式设计 - 手机屏幕 */
        @media screen and (max-width: 768px) {
            .header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            .header h1::before,
            .header h1::after {
                display: none;
            }
            .header-actions {
                margin-top: 15px;
                flex-wrap: wrap;
                justify-content: center;
                gap: 10px;
            }
            .search-container {
                flex-direction: column;
            }
            .search-container input[type="text"] {
                width: 100%;
                margin-bottom: 10px;
            }
            /* 表格转为卡片布局 */
            .ticket-table {
                display: block;
                width: 100%;
                overflow-x: auto;
            }
            .ticket-table th:nth-child(1),
            .ticket-table td:nth-child(1) {
                position: sticky;
                left: 0;
                background-color: #f5f7fa;
                z-index: 1;
            }
            /* 隐藏提交时间列 */
            .ticket-table th:nth-child(6),
            .ticket-table td:nth-child(6) {
                display: none;
            }
            .ticket-table th,
            .ticket-table td {
                padding: 8px 10px;
                font-size: 14px;
            }
            .view-btn, .delete-btn {
                padding: 5px 10px;
                font-size: 13px;
                margin-bottom: 5px;
                display: block;
                width: 100%;
            }
        }

        .ticket-table th,
        .ticket-table td {
            padding: 12px 15px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .ticket-table th {
            background-color: #f5f7fa;
            font-weight: 600;
        }
        .ticket-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .ticket-table tr:hover {
            background-color: #f1f1f1;
        }
        .view-btn {
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }
        .view-btn:hover {
            background-color: #2980b9;
        }
        .status-badge {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-pending {
            background-color: #f39c12;
            color: white;
        }
        .no-tickets {
            text-align: center;
            padding: 30px;
            color: #777;
        }
    
        /* 弹窗样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            width: 400px;
            max-width: 90%;
            padding: 25px;
            position: relative;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-header h2 {
            margin: 0;
            color: var(--primary);
            font-family: 'Ma Shan Zheng', cursive;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #777;
        }
        
        .modal-body {
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .cancel-btn {
            padding: 8px 15px;
            background-color: #95a5a6;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .save-btn {
            padding: 8px 15px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .change-username-btn,
        .change-password-btn {
            padding: 8px 15px;
            background-color: var(--secondary);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            text-decoration: none;
            display: inline-block;
        }
        
        .change-username-btn:hover,
        .change-password-btn:hover {
            background-color: #5ba8ff;
        }
        
        .change-password-btn:hover {
            background-color: #5ba8ff;
        }
        
        .password-success {
            background-color: #2ecc71;
            color: white;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            display: none;
        }
        
        .password-error {
            background-color: #e74c3c;
            color: white;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            display: none;
        }
</style>
</head>
<body>
    <div class="dashboard-container">
        <div class="header">
            <div class="anime-decoration"></div>
            <h1>Another Dimension Admin</h1>
            <div class="header-actions">
                <button id="change-username-btn" class="change-username-btn">
                <span>修改用户名</span>
                <span class="heart">♡</span>
            </button>
                <button id="change-password-btn" class="change-password-btn">
                <span>修改密码</span>
                <span class="heart">♡</span>
            </button>
                <a href="smtp_settings.php" class="smtp-btn">
                <span>SMTP设置</span>
                <span class="heart">♡</span>
            </a>
                <a href="?logout" class="logout-btn">
                <span>退出登录</span>
                <span class="heart">♡</span>
            </a>
            </div>
        </div>

        <h2>工单列表</h2>

        <?php if (isset($error)): ?>
            <div class="error-message"><?php echo $error; ?></div>
        <?php endif; ?>

        <?php if (!empty($success_message)): ?>
            <div class="success-message"><?php echo $success_message; ?></div>
        <?php endif; ?>

        <?php if (isset($_GET['success'])): ?>
            <div class="success-message"><?php echo $_GET['success']; ?></div>
        <?php endif; ?>

        <!-- 搜索表单 -->
        <div class="search-container">
            <form method="GET" action="admin_dashboard.php">
                <input type="text" name="search" placeholder="搜索工单 (工单ID、QQ号码、反馈类型、问题描述)..." value="<?php echo htmlspecialchars($searchKeyword); ?>">
                <button type="submit" class="search-btn">搜索</button>
                <?php if (!empty($searchKeyword)): ?>
                    <a href="admin_dashboard.php" class="reset-btn">重置</a>
                <?php endif; ?>
            </form>
        </div>

        <?php if (!empty($tickets)): ?>
            <!-- 批量操作工具栏 -->
            <div class="bulk-actions">
                <form method="POST" action="admin_dashboard.php">
                    <button type="submit" name="delete_selected" class="delete-btn" onclick="return confirm('确定要删除选中的工单吗？');">
                <span>删除选中</span>
                <span class="heart">♡</span>
            </button>
                    <table class="ticket-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select_all"></th>
                                <th>工单ID</th>
                                <th>QQ号码</th>
                                <th>反馈类型</th>
                                <th>严重程度</th>
                                <th>提交时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($tickets as $ticket): ?>
                                <tr>
                                    <td><input type="checkbox" name="selected_tickets[]" value="<?php echo $ticket['id']; ?>"></td>
                                    <td><?php echo $ticket['id']; ?></td>
                                    <td><?php echo $ticket['qq_number']; ?></td>
                                    <td><?php 
                                        $typeMap = [
                                            'account' => '账号问题',
                                            'function' => '功能故障',
                                            'suggestion' => '功能建议',
                                            'performance' => '性能问题',
                                            'security' => '安全问题',
                                            'other' => '其他问题'
                                        ];
                                        echo $typeMap[$ticket['feedback_type']] ?? $ticket['feedback_type'];
                                    ?></td>
                                    <td><?php 
                                        $stars = '';
                                        for ($i = 1; $i <= 5; $i++) {
                                            if ($i <= $ticket['severity']) {
                                                $stars .= '★';
                                            } else {
                                                $stars .= '☆';
                                            }
                                        }
                                        echo $stars;
                                    ?></td>
                                    <td><?php echo date('Y-m-d H:i:s', strtotime($ticket['created_at'])); ?></td>
                                    <td>
                                        <a href="view_ticket.php?id=<?php echo $ticket['id']; ?>" class="view-btn">
                    <span>查看详情</span>
                    <span class="heart">♡</span>
                </a>
                                        <a href="?delete_id=<?php echo $ticket['id']; ?>" class="delete-btn" onclick="return confirm('确定要删除这个工单吗？');">
                    <span>删除</span>
                    <span class="heart">♡</span>
                </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </form>
            </div>
        <?php else: ?>
            <div class="no-tickets">暂无工单数据</div>
        <?php endif; ?>
    </div>

    <!-- 修改用户名弹窗 -->
    <div id="username-modal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h2>✿ 修改用户名 ✿</h2>
                <button class="close-btn" id="close-username-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="username-success" class="password-success"></div>
                <div id="username-error" class="password-error"></div>
                <form id="change-username-form">
                    <div class="form-group">
                        <label for="current-username">当前用户名</label>
                        <input type="text" id="current-username" name="current-username" value="<?php echo htmlspecialchars($currentUsername); ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label for="new-username">新用户名</label>
                        <input type="text" id="new-username" name="new-username" required minlength="3" maxlength="20">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="cancel-btn" id="cancel-username-modal">取消</button>
                <button class="save-btn" id="save-username">保存修改</button>
            </div>
        </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div id="password-modal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h2>✿ 修改密码 ✿</h2>
                <button class="close-btn" id="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="password-success" class="password-success"></div>
                <div id="password-error" class="password-error"></div>
                <form id="change-password-form">
                    <div class="form-group">
                        <label for="current-password">当前密码</label>
                        <input type="password" id="current-password" name="current-password" required>
                    </div>
                    <div class="form-group">
                        <label for="new-password">新密码</label>
                        <input type="password" id="new-password" name="new-password" required minlength="6">
                    </div>
                    <div class="form-group">
                        <label for="confirm-password">确认新密码</label>
                        <input type="password" id="confirm-password" name="confirm-password" required minlength="6">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="cancel-btn" id="cancel-modal">取消</button>
                <button class="save-btn" id="save-password">保存修改</button>
            </div>
        </div>
    </div>

    <script>
        // 等待DOM完全加载后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 全选/取消全选功能
            const selectAllCheckbox = document.getElementById('select_all');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('input[name="selected_tickets[]"]');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                    });
                });
            }

            // 单个复选框改变时，更新全选框状态
            const checkboxes = document.querySelectorAll('input[name="selected_tickets[]"]');
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectAllStatus);
            });

            // 前端搜索功能
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    const searchTerm = this.value.toLowerCase();
                    const rows = document.querySelectorAll('.ticket-table tbody tr');
                    
                    rows.forEach(row => {
                        const ticketId = row.cells[1].textContent.toLowerCase();
                        const qqNumber = row.cells[2].textContent.toLowerCase();
                        const feedbackType = row.cells[3].textContent.toLowerCase();
                        const severity = row.cells[4].textContent.toLowerCase();
                        
                        if (ticketId.includes(searchTerm) ||
                            qqNumber.includes(searchTerm) || 
                            feedbackType.includes(searchTerm) || 
                            severity.includes(searchTerm)) {
                            row.style.display = '';
                        } else {
                            row.style.display = 'none';
                        }
                    });
                });
            }

            // 用户名和密码弹窗功能
            const usernameModal = document.getElementById('username-modal');
            const passwordModal = document.getElementById('password-modal');
            const changeUsernameBtn = document.getElementById('change-username-btn');
            const changePasswordBtn = document.getElementById('change-password-btn');
            const closeUsernameModal = document.getElementById('close-username-modal');
            const closePasswordModal = document.getElementById('close-modal');
            const cancelUsernameModal = document.getElementById('cancel-username-modal');
            const cancelPasswordModal = document.getElementById('cancel-modal');
            const saveUsernameBtn = document.getElementById('save-username');
            const savePasswordBtn = document.getElementById('save-password');

            // 打开用户名弹窗
            if (changeUsernameBtn && usernameModal) {
                changeUsernameBtn.addEventListener('click', function() {
                    usernameModal.style.display = 'flex';
                    // 重置消息和表单
                    document.getElementById('username-success').style.display = 'none';
                    document.getElementById('username-error').style.display = 'none';
                    document.getElementById('new-username').value = '';
                });
            }

            // 打开密码弹窗
            if (changePasswordBtn && passwordModal) {
                changePasswordBtn.addEventListener('click', function() {
                    passwordModal.style.display = 'flex';
                    // 重置消息和表单
                    document.getElementById('password-success').style.display = 'none';
                    document.getElementById('password-error').style.display = 'none';
                    document.getElementById('current-password').value = '';
                    document.getElementById('new-password').value = '';
                    document.getElementById('confirm-password').value = '';
                });
            }

            // 关闭用户名弹窗
            if (closeUsernameModal && usernameModal) {
                closeUsernameModal.addEventListener('click', function() {
                    usernameModal.style.display = 'none';
                });
            }

            // 关闭密码弹窗
            if (closePasswordModal && passwordModal) {
                closePasswordModal.addEventListener('click', function() {
                    passwordModal.style.display = 'none';
                });
            }

            // 取消用户名修改
            if (cancelUsernameModal && usernameModal) {
                cancelUsernameModal.addEventListener('click', function() {
                    usernameModal.style.display = 'none';
                });
            }

            // 取消密码修改
            if (cancelPasswordModal && passwordModal) {
                cancelPasswordModal.addEventListener('click', function() {
                    passwordModal.style.display = 'none';
                });
            }

            // 点击弹窗外部关闭弹窗
            window.addEventListener('click', function(event) {
                if (event.target === usernameModal) {
                    usernameModal.style.display = 'none';
                }
                if (event.target === passwordModal) {
                    passwordModal.style.display = 'none';
                }
            });

            // 保存用户名修改
            if (saveUsernameBtn) {
                saveUsernameBtn.addEventListener('click', function() {
                    const newUsername = document.getElementById('new-username').value.trim();
                    const successMsg = document.getElementById('username-success');
                    const errorMsg = document.getElementById('username-error');

                    // 简单前端验证
                    if (newUsername.length < 3 || newUsername.length > 20) {
                        errorMsg.textContent = '用户名长度必须在3-20个字符之间';
                        errorMsg.style.display = 'block';
                        successMsg.style.display = 'none';
                        return;
                    }

                    // 发送AJAX请求
                    fetch('admin_dashboard.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'change_username=1&new_username=' + encodeURIComponent(newUsername)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            successMsg.textContent = data.message;
                            successMsg.style.display = 'block';
                            errorMsg.style.display = 'none';
                            // 更新当前用户名显示
                            document.getElementById('current-username').value = newUsername;
                            // 3秒后关闭弹窗
                            setTimeout(() => {
                                usernameModal.style.display = 'none';
                            }, 1500);
                        } else {
                            errorMsg.textContent = data.message;
                            errorMsg.style.display = 'block';
                            successMsg.style.display = 'none';
                        }
                    })
                    .catch(error => {
                        errorMsg.textContent = '操作失败，请重试';
                        errorMsg.style.display = 'block';
                        successMsg.style.display = 'none';
                        console.error('Error:', error);
                    });
                });
            }

            // 保存密码修改
            if (savePasswordBtn) {
                savePasswordBtn.addEventListener('click', function() {
                    const currentPassword = document.getElementById('current-password').value;
                    const newPassword = document.getElementById('new-password').value;
                    const confirmPassword = document.getElementById('confirm-password').value;
                    const successMsg = document.getElementById('password-success');
                    const errorMsg = document.getElementById('password-error');

                    // 简单前端验证
                    if (newPassword !== confirmPassword) {
                        errorMsg.textContent = '两次输入的新密码不一致';
                        errorMsg.style.display = 'block';
                        successMsg.style.display = 'none';
                        return;
                    }

                    if (newPassword.length < 6) {
                        errorMsg.textContent = '密码长度必须至少6个字符';
                        errorMsg.style.display = 'block';
                        successMsg.style.display = 'none';
                        return;
                    }

                    // 发送AJAX请求
                    fetch('admin_dashboard.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'change_password=1&current_password=' + encodeURIComponent(currentPassword) +
                               '&new_password=' + encodeURIComponent(newPassword) +
                               '&confirm_password=' + encodeURIComponent(confirmPassword)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            successMsg.textContent = data.message;
                            successMsg.style.display = 'block';
                            errorMsg.style.display = 'none';
                            // 重置表单
                            document.getElementById('current-password').value = '';
                            document.getElementById('new-password').value = '';
                            document.getElementById('confirm-password').value = '';
                            // 3秒后关闭弹窗
                            setTimeout(() => {
                                passwordModal.style.display = 'none';
                            }, 1500);
                        } else {
                            errorMsg.textContent = data.message;
                            errorMsg.style.display = 'block';
                            successMsg.style.display = 'none';
                        }
                    })
                    .catch(error => {
                        errorMsg.textContent = '操作失败，请重试';
                        errorMsg.style.display = 'block';
                        successMsg.style.display = 'none';
                        console.error('Error:', error);
                    });
                });
            }
        });

        function updateSelectAllStatus() {
            const selectAllCheckbox = document.getElementById('select_all');
            const checkboxes = document.querySelectorAll('input[name="selected_tickets[]"]');
            const checkedCheckboxes = document.querySelectorAll('input[name="selected_tickets[]"]:checked');
            
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = checkboxes.length === checkedCheckboxes.length && checkboxes.length > 0;
            }
        }
    </script>
    <script src="script_anime_admin.js"></script>
</body>
</html>
